package com.wb.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 魏彪
 * 此类不是真正的代理类，真正的代理类在jvm内存中，一般以$Proxy的形式出现
 */
public class TargetProxy implements InvocationHandler {

    private Object target;

    public TargetProxy(Object target) {
        this.target = target;
    }

    /**
     * 获取真正的代理类
     * @param interfaces
     * @return
     * @param <T>
     */
    public <T> T getProxy(Class<?> interfaces) {
        return (T) Proxy.newProxyInstance(interfaces.getClassLoader(), new Class<?>[]{interfaces}, this);
    }

    /**
     * @param proxy  这个就是我们那个代理类，就是jdk生成的那个$proxy.代理类
     * @param method 就是目标接口的方法，比如sayHi(),work()的反射对象Method;
     * @param args   an array of objects containing the values of the
     *               arguments passed in the method invocation on the proxy instance,
     *               or {@code null} if interface method takes no arguments.
     *               Arguments of primitive types are wrapped in instances of the
     *               appropriate primitive wrapper class, such as
     *               {@code java.lang.Integer} or {@code java.lang.Boolean}.
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("前置增强通知......");

        Object result = method.invoke(target, args);

        System.out.println("后置增强通知......");
        return result;
    }
}
